package com.example.safeassistan.home.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.constants.Constants;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.adapter.OverDueTaskAdapter;
import com.example.safeassistan.home.adapter.WarnningListAdapter;
import com.example.safeassistan.home.model.OverDueTaskListModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.model.WarningListModel;
import com.example.safeassistan.utile.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class WarnningList extends BaseActivity implements View.OnClickListener {
    private WarnningListAdapter adapter;
    private RecyclerView rcView;
    private SmartRefreshLayout refresh;
    private List<WarningListModel.ResultDTO.RecordsDTO> data;
    private TextView _barTvRight;
    private ImageView _barBack;
    private Toolbar _barToolbar;
    private LinearLayout llNodata;



    private Integer currentPage=1;
    private int count=0;
    private String checkTime="";
    private String level="";
    private String checkStatus="-1"; //0 我的 1 部门
    private String riskpointId="";

    public static void actionStart(Context context,String checkStatus,String riskpointId) {
        Intent intent = new Intent(context, WarnningList.class);
        intent.putExtra("checkStatus",checkStatus);
        intent.putExtra("riskpointId",riskpointId);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.warnning_list;
    }

    @Override
    protected void initView() {
        checkStatus=getIntent().getStringExtra("checkStatus");
        riskpointId=getIntent().getStringExtra("riskpointId");
        rcView=findViewById(R.id.rcView);
        _barTvRight=findViewById(R.id._barTvRight);
        _barTvRight.setOnClickListener(this);
        _barBack=findViewById(R.id._barBack);
        refresh=findViewById(R.id.refresh);
        llNodata=findViewById(R.id.llNodata);
        _barBack.setOnClickListener(this::onClick);
        _barToolbar=findViewById(R.id._barToolbar);


        setView();
        getData();
    }


    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    public void getData(){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("checkStatus",checkStatus);
            jsonObject.put("pageNo",currentPage);
            jsonObject.put("pageSize", Constants.PAGESIZE);
            if (!checkTime.equals("")){
                jsonObject.put("checkTime",checkTime);

            }
            if (!riskpointId.equals("")){
                jsonObject.put("riskpointId",riskpointId);
            }

            if (!level.equals("")){
                jsonObject.put("level",level);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(WarnningList.this).doPost(UrlConstants.queryWarnRiskPoint, null,jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean  success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), WarningListModel.class);
                        if (obj instanceof WarningListModel) {
                            WarningListModel  backLogListModel=(WarningListModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = backLogListModel.getResult().getTotal();
                                if (backLogListModel.getResult().getRecords().size()>0){
                                    rcView.setVisibility(View.VISIBLE);
                                    llNodata.setVisibility(View.GONE);
                                    data=backLogListModel.getResult().getRecords();
                                    rcView.setLayoutManager(new LinearLayoutManager(WarnningList.this));
                                    adapter=new WarnningListAdapter(data);
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                }else {
                                    rcView.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                }
                            }else {
                                data.addAll(backLogListModel.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(WarnningList.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }
    PopupWindow popupWindow;
    TextView tvSelect1,tvSelect2,tvSelect3,tvSelect4,tvSure,tvReSet;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id._barTvRight:
                //筛选
                View inflate = LayoutInflater.from(getContext()).inflate(R.layout.dialog_warnning_top,null);
                popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
               LinearLayout llChiose=inflate.findViewById(R.id.llChiose);
                TextView tvCheckTime=inflate.findViewById(R.id.tvCheckTime);
                tvSelect1=inflate.findViewById(R.id.tvSelect1);
                 tvSelect2=inflate.findViewById(R.id.tvSelect2);
                 tvSelect3=inflate.findViewById(R.id.tvSelect3);
                 tvSelect4=inflate.findViewById(R.id.tvSelect4);
                tvReSet=inflate.findViewById(R.id.tvReSet);
                tvReSet.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //重置
                        level="";
                        checkTime="";
                        tvCheckTime.setHint("请选择检查日期");
                    }
                });
                tvSure=inflate.findViewById(R.id.tvSure);
                tvSure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        getData();
                    }
                });


                tvSelect1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reSetStatus();
                        level="1";
                        tvSelect1.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                        tvSelect1.setBackgroundResource(R.drawable.stoke_blue_bg);
                    }
                });
                 tvSelect2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reSetStatus();
                        level="2";
                        tvSelect2.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                        tvSelect2.setBackgroundResource(R.drawable.stoke_blue_bg);
                    }
                });
                  tvSelect3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reSetStatus();
                        level="3";
                        tvSelect3.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                        tvSelect3.setBackgroundResource(R.drawable.stoke_blue_bg);
                    }
                });
                   tvSelect4.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reSetStatus();
                        level="4";
                        tvSelect4.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                        tvSelect4.setBackgroundResource(R.drawable.stoke_blue_bg);
                    }
                });

                llChiose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TimePickerView endTime = new TimePickerBuilder(WarnningList.this, new OnTimeSelectListener() {
                            @Override
                            public void onTimeSelect(Date date, View v) {//选中事件回调
                                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
                                checkTime=simpleDateFormat.format(date);
                                tvCheckTime.setText(simpleDateFormat.format(date));
                            }
                        })
                                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                                .setCancelText("取消")//取消按钮文字
                                .isDialog(true)
                                .setSubmitText("确定")//确认按钮文字
                                .setTitleSize(18)//标题文字大小
                                .setTitleColor(getResources().getColor(R.color.white))
                                .setTitleText("检查日期")
                                .setContentTextSize(17)
                                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                                .isCyclic(true)//是否循环滚动
                                .setTextColorOut(getResources().getColor(R.color.gray6))
                                .setTextColorCenter(getResources().getColor(R.color.blue_3B5BEA))
                                .setSubmitColor(getResources().getColor(R.color.white))//确定按钮文字颜色
                                .setLabel("年", "月", "日", "时", "分", "秒")//默认设���为年月日时分秒
                                .isCenterLabel(false) //是否只显示中间选中项的 label 文字，false 则每项 item 全部都带有 label。
                                .build();
                        endTime.show();
                    }
                });
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(_barToolbar,0,0);
                break;
            case R.id._barBack:
                finish();
                break;
        }
    }

    public void reSetStatus() {
        tvSelect1.setTextColor(getResources().getColor(R.color.gray9));
        tvSelect2.setTextColor(getResources().getColor(R.color.gray9));
        tvSelect3.setTextColor(getResources().getColor(R.color.gray9));
        tvSelect4.setTextColor(getResources().getColor(R.color.gray9));
        tvSelect1.setBackgroundResource(R.drawable.stoke_gray_22_bg);
        tvSelect2.setBackgroundResource(R.drawable.stoke_gray_22_bg);
        tvSelect3.setBackgroundResource(R.drawable.stoke_gray_22_bg);
        tvSelect4.setBackgroundResource(R.drawable.stoke_gray_22_bg);
    }
}